﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace qiniuUI
{
    public partial class download : Form
    {
        //存放下载列表
        List<SynFileInfo> m_SynFileInfoList;
        List<ArrayList> down_file_list4UI;

        public download()
        {
            InitializeComponent();
            down_file_list4UI = new List<ArrayList>();
            m_SynFileInfoList = new List<SynFileInfo>();
            this.ControlBox = false;
        }
        public void myshow(List<string> downloadList, string path)
        {
            this.Show();
            //设置最大活动线程数以及可等待线程数
            ThreadPool.SetMaxThreads(10, 10);
            int i = 0;
            int j = 0;
            foreach (string str in downloadList)
            {
                for (j = 0; j < down_file_list4UI.Count; j++)
                {
                    if (down_file_list4UI[j].Contains(str))
                    {
                        break;
                    }
                }
                if (j == down_file_list4UI.Count)
                {
                    ArrayList tmp = new ArrayList();
                    tmp.Add(i + "");
                    tmp.Add(str);
                    tmp.Add(0 + "");
                    tmp.Add(0 + "KB/s");
                    tmp.Add(0 + "%");
                    tmp.Add(ConfigHelper.GetConnectionStringsConfig("server_url") + str);
                    tmp.Add(path + str);
                    down_file_list4UI.Add(tmp);
                    i++;
                    add_batch_download(tmp);
                    if (isConnected())
                    {
                        StartDownLoad(m_SynFileInfoList.ElementAt(m_SynFileInfoList.Count - 1));
                    }
                    else
                    {
                        MessageBox.Show("网络异常!");
                    }
                }
            }
        }
        void StartDownLoad(object o)
        {
            SynFileInfo m_SynFileInfo = (SynFileInfo)o;
            m_SynFileInfo.LastTime = DateTime.Now;
            //再次new 避免WebClient不能I/O并发 
            WebClient client = new WebClient();
            //异步下载
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadFileAsync(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath, m_SynFileInfo);
        }

        private void hidden_bt_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void download_Load(object sender, EventArgs e)
        {
            init_downloadlist(downlist);
            add_downloadlist(downlist);
        }
        void init_downloadlist(DataGridView dgv)
        {
            dgv.AutoGenerateColumns = false;//是否自动创建列
            dgv.AllowUserToAddRows = false;//是否允许添加行(默认：true)
            dgv.AllowUserToDeleteRows = false;//是否允许删除行(默认：true)
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列宽模式(当前填充)(默认：DataGridViewAutoSizeColumnsMode.None)
            dgv.BackgroundColor = System.Drawing.Color.White;//背景色(默认：ControlDark)
            dgv.BorderStyle = BorderStyle.Fixed3D;//边框样式(默认：BorderStyle.FixedSingle)
            dgv.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;//单元格边框样式(默认：DataGridViewCellBorderStyle.Single)
            dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;//列表头样式(默认：DataGridViewHeaderBorderStyle.Single)
            dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;//是否允许调整列大小(默认：DataGridViewColumnHeadersHeightSizeMode.EnableResizing)
            dgv.ColumnHeadersHeight = 30;//列表头高度(默认：20)
            dgv.MultiSelect = false;//是否支持多选(默认：true)
            dgv.ReadOnly = true;//是否只读(默认：false)
            dgv.RowHeadersVisible = false;//行头是否显示(默认：true)
            dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//选择模式(默认：DataGridViewSelectionMode.CellSelect)

        }
        void add_downloadlist(DataGridView dgv)
        {
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "keyID",
                HeaderText = "keyID",
                Visible = false,
                Name = "keyID"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
                DataPropertyName = "keyName",
                HeaderText = "key名",
                Name = "keyName",
                Width = 300
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "FileSize",
                HeaderText = "大小",
                Name = "FileSize",
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "SynSpeed",
                HeaderText = "速度",
                Name = "SynSpeed"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "SynProgress",
                HeaderText = "进度",
                Name = "SynProgress"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "DownPath",
                HeaderText = "下载地址",
                Name = "DownPath"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "SavePath",
                HeaderText = "保存地址",
                Name = "SavePath"
            });
        }
        private void download_SizeChanged(object sender, EventArgs e)
        {
            hidden_bt.Location = new System.Drawing.Point(this.Size.Width - hidden_bt.Size.Width - 20, this.Size.Height - hidden_bt.Size.Height - 50); ;
            downlist.Size = new System.Drawing.Size(this.Size.Width - 20, this.Size.Height - hidden_bt.Size.Height - 50); ;
        }
        private void add_batch_download(ArrayList downloadList)
        {
            //添加列表(建立多个任务)
            int rowIndex = downlist.Rows.Add(downloadList.ToArray());
            if (downloadList.Count > 7)
            {
                downloadList.RemoveAt(7);
            }
            downloadList.Add(downlist.Rows[rowIndex]);
            //取出列表中的行信息保存列表集合(m_SynFileInfoList)中
            m_SynFileInfoList.Add(new SynFileInfo(downloadList.ToArray()));
        }
        //检测网络状态
        [DllImport("wininet.dll")]
        extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        /// <summary>
        /// 检测网络状态
        /// </summary>
        bool isConnected()
        {
            int I = 0;
            bool state = InternetGetConnectedState(out I, 0);
            return state;
        }
        /// <summary>
        /// 下载进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState;
            m_SynFileInfo.RowObject.Cells["FileSize"].Value = FileOperate.GetAutoSizeString(Convert.ToDouble(e.TotalBytesToReceive), 2);
            m_SynFileInfo.SynProgress = e.ProgressPercentage + "%";
            double secondCount = (DateTime.Now - m_SynFileInfo.LastTime).TotalSeconds;
            m_SynFileInfo.SynSpeed = FileOperate.GetAutoSizeString(Convert.ToDouble(e.BytesReceived / secondCount), 2) + "/s";
            //更新DataGridView中相应数据显示下载进度
            m_SynFileInfo.RowObject.Cells["SynProgress"].Value = m_SynFileInfo.SynProgress;
            //更新DataGridView中相应数据显示下载速度(总进度的平均速度)
            m_SynFileInfo.RowObject.Cells["SynSpeed"].Value = m_SynFileInfo.SynSpeed;
        }

        /// <summary>
        /// 下载完成调用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //到此则一个文件下载完毕
            SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState;
        }
        /// <summary>
        /// 文件有关的操作类
        /// </summary>
        public class FileOperate
        {
            #region 相应单位转换常量

            private const double KBCount = 1024;
            private const double MBCount = KBCount * 1024;
            private const double GBCount = MBCount * 1024;
            private const double TBCount = GBCount * 1024;

            #endregion

            #region 获取适应大小

            /// <summary>
            /// 得到适应大小
            /// </summary>
            /// <param name="size">字节大小</param>
            /// <param name="roundCount">保留小数(位)</param>
            /// <returns></returns>
            public static string GetAutoSizeString(double size, int roundCount)
            {
                if (KBCount > size) return Math.Round(size, roundCount) + "B";
                else if (MBCount > size) return Math.Round(size / KBCount, roundCount) + "KB";
                else if (GBCount > size) return Math.Round(size / MBCount, roundCount) + "MB";
                else if (TBCount > size) return Math.Round(size / GBCount, roundCount) + "GB";
                else return Math.Round(size / TBCount, roundCount) + "TB";
            }

            #endregion
        }

        private void opendiret_Click(object sender, EventArgs e)
        {

        }

        private void downlist_MouseDown(object sender, MouseEventArgs e)
        {

        }
    }
}
